package com.xy.mainp.main.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.xy.debug.LogUtils;
import com.xy.img.GlideUtil;
import com.xy.mainp.FragmentMsgBinding;
import com.xy.mainp.R;
import com.xy.mainp.base.TittleBarFragmnet;
import com.xy.mainp.huaban.fragment.ImagFragment;
import com.xy.mainp.huaban.utils.SearchUtil;
import com.xy.mainp.main.widget.TittleBar;
import com.xy.mainp.model.huaban.ImgCategoryEntity;
import com.xy.mainp.model.huaban.ImgEntity;
import com.xy.mainp.huaban.widget.HistoryPopup;
import com.xy.mainp.huaban.widget.ItemImgView;
import com.xy.mainp.model.huaban.SearchHistoryEntity;
import com.xy.mainp.utils.NetRequestUtils;
import com.xy.net.OkHttpUtils;
import com.xy.view.recyclerview.StandardAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.Request;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by John on 2016/10/28.
 */

public class HuaBanFragment extends TittleBarFragmnet {

    private FragmentMsgBinding binding;
    private String Result;
    private EditText etTittle;
    private HistoryPopup historyPopup;
    private SearchUtil searchUtil;
    private List<SearchHistoryEntity> searchHistoryEntities = new ArrayList<>();
    private ArrayList<ImgCategoryEntity> categories = new ArrayList<>();
    private List<ImagFragment> fragments;
    private HuaBanVPAdapter huaBanVPAdapter;
    private String SearchText;



    @Override
    protected void onIn() {
        super.onIn();
        binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_huaban, null, false);
        setContentView(binding.getRoot());
        initView();
        GlideUtil.clearMemory(getContext());
    }

    @Override
    protected void onShow() {
        super.onShow();
        loadData();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        GlideUtil.clearMemory(getContext());
    }

    private void loadData() {
        SearchText = "清新美女";
        searchUtil = SearchUtil.getInstance(getContext());
        searchHistoryEntities = searchUtil.getAllData();
        loadNetData(SearchText, null, "1", "20", "1");
    }

    private boolean search = false;

    private void initView() {
        huaBanVPAdapter = new HuaBanVPAdapter(getFragmentManager());
        binding.vpHuaban.setAdapter(huaBanVPAdapter);
        binding.tlHuaban.setViewPager(binding.vpHuaban);
        initTitleBar();
        initHistoryP();
        initEtTittle();


    }

    private void initEtTittle() {
        etTittle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus && searchHistoryEntities.size() != 0) {
                    historyPopup.show(etTittle);
                }
            }
        });
        etTittle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (etTittle.getText() != null && !TextUtils.isEmpty(etTittle.getText().toString())) {
                    String tempName = etTittle.getText().toString();
                    // 根据tempName去模糊查询数据库中有没有数据
                    searchHistoryEntities = searchUtil.searchData(tempName);
                    if (searchHistoryEntities.size() != 0) {
                        if (searchHistoryEntities.size() >= 10) {
                            searchHistoryEntities = searchHistoryEntities.subList(0, 10);
                        }
                        historyPopup.setData(searchHistoryEntities);
                        if (!historyPopup.isShowing()) {
                            historyPopup.show(etTittle);
                        }
                    } else {
                        if (historyPopup.isShowing()) {
                            historyPopup.dismiss();
                        }
                    }
                }
            }
        });
        etTittle.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    //先隐藏软键盘
                    ((InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getActivity()
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    Editable searchtext = etTittle.getText();
                    if (!TextUtils.isEmpty(searchtext)) {
                        SearchHistoryEntity searchHistoryEntity = new SearchHistoryEntity();
                        searchHistoryEntity.setText(searchtext.toString());
                        searchHistoryEntity.setcTime(System.currentTimeMillis());
                        if (!searchUtil.hasData(searchtext.toString())) {
                            searchUtil.insertData(searchHistoryEntity);
                        } else {
                            searchUtil.updateData(searchHistoryEntity, "text = ?", new String[]{searchtext.toString()});
                        }
                        SearchText = searchtext.toString().trim();
                        loadNetData(SearchText, null, null, null, null);
                    } else {
                        showToastMsg("请输入搜索内容");
                    }
                }
                return false;
            }
        });
    }

    private void initHistoryP() {
        historyPopup = new HistoryPopup(getContext());
        historyPopup.setItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                etTittle.setText(((TextView) view).getText());
                if (historyPopup.isShowing()) {
                    historyPopup.dismiss();
                }
            }
        });
    }

    private void initTitleBar() {
        final TittleBar tittleBar = getTittleBar();
        tittleBar.canSearch(true);
        tittleBar.setItemClick(TittleBar.ITEM_SEARCH, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tittleBar.setVisEditText(!search);
                search = !search;
            }
        });
        etTittle = tittleBar.getEtTittle();
        etTittle.setHint("请输入搜索内容");
        etTittle.setHintTextColor(getResources().getColor(R.color.black_80_2c));
    }


    private void loadNetData(String p, String category, String page, String prePage, String wlf) {
        showLoading(true);
        try {
            NetRequestUtils.getInstance(getContext()).getHuaBanData(p, category, page, prePage, wlf, new OkHttpUtils.ResultCallBack<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    showLoading(false);
                    showToastMsg(e.getMessage());
                }

                @Override
                public void onResult(String result) {
                    Result = result;
                    final Document document = Jsoup.parse(Result);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            loadCategoryData(document);
                        }
                    }).start();
                }
            });
        } catch (IOException e) {
            showToastMsg(e.getMessage());
            e.printStackTrace();
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (categories.get(0).getTitle().contains("(0)")) {
                showToastMsg("搜索不到相关图片");
            } else {
                binding.vpHuaban.removeAllViews();
                huaBanVPAdapter.setData(categories);
                huaBanVPAdapter.notifyDataSetChanged();
            }
        }
    };
    private void loadCategoryData(Document document) {
        showLoading(false);
        Element element = document.select("ul").first();
        categories = new ArrayList<>();
        Elements lis = element.select("li");
        Element isSlect = lis.select("[class=now-on]").first();
        for (Element e : lis) {
            ImgCategoryEntity imgCategoryEntity = new ImgCategoryEntity();
            imgCategoryEntity.setTitle(e.text());
            if (e == isSlect) {
                imgCategoryEntity.setSelected(true);
            }
            imgCategoryEntity.setCategoryUrl(e.select("a").attr("href").toString());
            LogUtils.i(e.select("a").attr("href").toString());
            categories.add(imgCategoryEntity);
        }
        categories.get(0).setCategoryUrl("/search/?q=" + (TextUtils.isEmpty(etTittle.getText().toString().trim()) ? SearchText : etTittle.getText().toString().trim()));
        handler.obtainMessage().sendToTarget();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (historyPopup != null && historyPopup.isShowing()) {
            historyPopup.dismiss();
            historyPopup = null;
        }
    }

    class HuaBanVPAdapter extends FragmentStatePagerAdapter {

        private ArrayList<ImgCategoryEntity> data;
        private ImagFragment mCurrentFragment;

        public HuaBanVPAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return data != null ? data.size() : 0;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return data != null ? data.get(position).getTitle() : "";
        }

        public void setData(ArrayList<ImgCategoryEntity> data) {
            this.data = data;
            initFragments();
        }

        private void initFragments() {
            fragments = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                fragments.add(new ImagFragment(data.get(i).getCategoryUrl()));
            }
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
            this.mCurrentFragment = (ImagFragment) object;
        }

        public ImagFragment getPrimaryItem() {
            return mCurrentFragment;
        }
    }

}
